#include"mainscene.h"
#include"config.h"
#include<QIcon>
#include<QPainter>
#include<QMouseEvent>
#include<ctime>
#include <QKeyEvent>
#include <QLabel>
#include <QApplication>
Widget::Widget(QWidget *parent)
    : QWidget(parent)
{
    //调用初始化
    initscene();
    initPauseButton();
    //初始背景
    m_gameStarted = false;
    //启动游戏
    //playgame();
    // 初始化背景音乐
    m_backgroundSound.setSource(QUrl(SOUND_BACKGROUND));
    m_backgroundSound.setVolume(0.5); // 设置音量，范围是0.0 - 1.0
    m_backgroundSound.setLoopCount(QSoundEffect::Infinite); // 设置为无限循环播放
    m_backgroundSound.play();
    m_enemy1_destroyedCount=0;
    m_enemy2_destroyedCount=0;
    // 游戏初始状态为未暂停
}
Widget::~Widget() {
}
//页面初始化
void Widget::initscene()
{
    //设置窗口固定尺寸
    setFixedSize(GAME_WIDTH,GAME_HEIGHT);
    //设置标题
    setWindowTitle(GAME_TITLE);
    setWindowIcon(QIcon(GAME_ICON));
        //定时器
    m_Timer.setInterval(GAME_RATE);
    //敌机初始间隔间隔 1
    m_recorder=0;
    m_recorder2=0;
    //随机数种子
    srand((unsigned int)time(NULL));
    //血条初值
    m_heroHP = 3;
    //初始背景
    // 创建开始游戏按钮（覆盖在“开始游戏”字样区域）
    m_startBtn = new QPushButton(this);
    m_startBtn->setText("");  // 不显示文字
    m_startBtn->setStyleSheet("background: transparent; border: none;");

    // 按钮位置
    m_startBtn->setGeometry(140, 400, 200, 50);
    m_startBtn->show();

    connect(m_startBtn, &QPushButton::clicked, this, [=]() {
        m_gameStarted = true;
        m_startBtn->hide();
        //开始游戏
        playgame();
    });
    update();
}

void Widget::playgame()
{

    //启动定时
    m_Timer.start();
    //监听
    connect(&m_Timer,&QTimer::timeout,this,[=](){
        //敌机1出场
        enemyToscene();
        //敌机2出场
        enemyToscene2();
        //更新坐标
        updateposition();
        //绘制
        update();
        //碰撞检测1
        collosionDEtection();
        //碰撞检测2
        collosionDEtection2();
    });

}
void Widget::updateEnemy2Bullets()
{
    for (int i = 0; i < ENEMY2_NUM; ++i)
    {
        if (!m_enemys2[i].m_Free)
        {
            for (int j = 0; j < BULLET_ENEMY_NUM; ++j)
            {
                if (!m_enemys2[i].enemy_bullets[j].m_Free)
                {
                    m_enemys2[i].enemy_bullets[j].updatePosition2();
                }
            }
        }
    }
}

void Widget::initPauseButton()
{
    //中间暂停
    m_pauseBtn = new QPushButton(this);
    m_pauseBtn->setIcon(QIcon(GAME_PAUSE));
    m_pauseBtn->setIconSize(QSize(50, 50));
    m_pauseBtn->move(GAME_WIDTH - 60, 10); // 右上角位置
    m_pauseBtn->setFlat(true); // 去掉边框

    connect(m_pauseBtn, &QPushButton::clicked, this, [=]() {
        if (m_isPaused) {
            // 恢复游戏
            m_Timer.start();
            m_backgroundSound.play();
            m_pauseBtn->setIcon(QIcon(GAME_PAUSE));
            m_isPaused = false;
        } else {
            // 暂停游戏
            m_Timer.stop();
            m_backgroundSound.stop();
            m_pauseBtn->setIcon(QIcon(PAUSE_RESUME ));
            m_isPaused = true;
            update();
        }
    });
}

void Widget::keyPressEvent(QKeyEvent *event)
{
    if (event->key() == Qt::Key_Escape) {
        showGameOverScreen();
    }
}

void Widget::showGameOverScreen()
{
    // 停止游戏
    m_Timer.stop();
    m_backgroundSound.stop();

    // 创建背景
    m_gameOverBackground = new QLabel(this);
    m_gameOverBackground->setPixmap(QPixmap(GAME_OVER_BACKGROUND));
    m_gameOverBackground->setGeometry(0, 0, GAME_WIDTH, GAME_HEIGHT);
    m_gameOverBackground->show();

    // 按钮1：退出
    m_btnGameOver = new QPushButton(this);
    m_btnGameOver->setIcon(QIcon(GANE_OVER_TEXT1));
    m_btnGameOver->setIconSize(QSize(200, 50));
    m_btnGameOver->move((GAME_WIDTH - 200) / 2, GAME_HEIGHT / 2 - 60);
    m_btnGameOver->show();

    // 按钮2：再来一次
    m_btnAgain = new QPushButton(this);
    m_btnAgain->setIcon(QIcon(GANE_OVER_TEXT2));
    m_btnAgain->setIconSize(QSize(200, 50));
    m_btnAgain->move((GAME_WIDTH - 200) / 2, GAME_HEIGHT / 2 + 10);
    m_btnAgain->show();

    connect(m_btnAgain, &QPushButton::clicked, this, [=]() {
        restartGame();
    });

    connect(m_btnGameOver, &QPushButton::clicked, this, [=]() {
        qApp->quit();
    });
    //
    m_gameOverStats = new QLabel(this);
    m_gameOverStats->setGeometry(0, GAME_HEIGHT / 2 + 80, GAME_WIDTH, 100); // 位置在两个按钮下方

    QString statsText = QString("敌机1 击毁数: %1\n敌机2 击毁数: %2")
                            .arg(m_enemy1_destroyedCount)
                            .arg(m_enemy2_destroyedCount);

    m_gameOverStats->setText(statsText);
    m_gameOverStats->setAlignment(Qt::AlignCenter);
    m_gameOverStats->setStyleSheet("color: white; font-size: 20px; background-color: rgba(0,0,0,150);");
    m_gameOverStats->show();
}

void Widget::restartGame()
{
    if (m_gameOverBackground) {
        m_gameOverBackground->hide();
        delete m_gameOverBackground;
        m_gameOverBackground = nullptr;
    }
    if (m_btnGameOver) {
        m_btnGameOver->hide();
        delete m_btnGameOver;
        m_btnGameOver = nullptr;
    }
    if (m_btnAgain) {
        m_btnAgain->hide();
        delete m_btnAgain;
        m_btnAgain = nullptr;
    }

    // 重置玩家位置
    m_hero.setPosition(GAME_WIDTH / 2 - m_hero.m_Rect.width() / 2,
                       GAME_HEIGHT - m_hero.m_Rect.height() - 50);

    // 重置敌人状态
    for (int i = 0; i < ENEMY1_NUM; ++i) {
        m_enemys[i].m_Free = true;
    }
    for (int i = 0; i < ENEMY2_NUM; ++i) {
        m_enemys2[i].m_Free = true;
    }

    // 重置爆炸效果
    for (int i = 0; i < BOMB_ENEMY1_NUM; ++i) {
        m_enemy1_bombs[i].m_Free = true;
    }
    for (int i = 0; i < BOMB_ENEMY2_NUM; ++i) {
        m_enemy2_bombs[i].m_Free = true;
    }

    // 重置分数
    m_enemy1_destroyedCount = 0;
    m_enemy2_destroyedCount = 0;

    // 重置暂停状态
    m_isPaused = false;
    m_pauseBtn->setIcon(QIcon(GAME_PAUSE));

    // 重新启动定时器和背景音乐
    m_Timer.start();
    m_backgroundSound.play();
    if (m_gameOverStats) {
        m_gameOverStats->hide();
        delete m_gameOverStats;
        m_gameOverStats = nullptr;
    }
    m_heroHP = 3;
}


void Widget::updateposition()
{
    //更新地图坐标重要
    m_map.mapPOSITION();
    //发射子弹
    m_hero.shoot();
    //计算非空闲子弹坐标坐标

    for (int i = 0; i < BULLET_MY_NUM; ++i) {
        //非空闲，计算发射位置
        if(m_hero.m_bullets[i].m_Free==false){
            m_hero.m_bullets[i].updatePosition();
        }
    }
    //敌机1出场
    for (int i = 0; i < ENEMY1_NUM; ++i) {
        if(m_enemys[i].m_Free==false){
            m_enemys[i].upadatePosition();
        }
    }
    // 敌机2出场
    for (int i = 0; i < ENEMY2_NUM; ++i) {
        if (m_enemys2[i].m_Free == false) {
            m_enemys2[i].upadatePosition();
            //敌机发射子弹
            m_enemys2[i].shoot();
        }
    }
    //爆炸1计算
    for (int i = 0; i <BOMB_ENEMY1_NUM; ++i) {
        if(m_enemy1_bombs[i].m_Free==false){
            m_enemy1_bombs[i].updateInfo();
        }
    }
    //爆炸2计算
    for (int i = 0; i <BOMB_ENEMY1_NUM; ++i) {
        if(m_enemy2_bombs[i].m_Free==false){
            m_enemy2_bombs[i].updateInfo2();
        }
    }
    //爆炸3计算
    for (int i = 0; i < BOMB_ME_NUM; ++i) {
        if (!m_meBombs[i].m_Free) {
            m_meBombs[i].updateInfo();
        }
    }
    updateEnemy2Bullets();
    //测试
    // temp_bullet.m_Free=false;
    // temp_bullet.updatePosition();
    collosionDEtection3();
}

//绘画**********
void Widget::paintEvent(QPaintEvent *)
{
    QPainter painter(this);

    if (!m_gameStarted) {
        // 游戏未开始时，画启动界面背景
        QPixmap startBg(GAME_RE_MAPPATH);
        painter.drawPixmap(0, 0, GAME_WIDTH, GAME_HEIGHT, startBg);
        return;  // 不画其他内容
    }

    painter.drawPixmap(0,m_map.m_map1_posy,m_map.m_map1);
    painter.drawPixmap(0,m_map.m_map2_posy,m_map.m_map2);
    //绘制我方飞机
    painter.drawPixmap(m_hero.m_x,m_hero.m_y,m_hero.m_plane);
    //测试子弹
    //painter.drawPixmap(temp_bullet.m_X,temp_bullet.m_Y,temp_bullet.m_bullet);
    for (int i = 0; i < BULLET_MY_NUM; ++i) {
        //非空闲，绘画

        if(m_hero.m_bullets[i].m_Free==false){
            painter.drawPixmap(m_hero.m_bullets[i].m_X,m_hero.m_bullets[i].m_Y,m_hero.m_bullets[i].m_bullet);
        }

    }
    //敌机
    for (int i = 0; i < ENEMY1_NUM; ++i)
    {
        if (!m_enemys[i].m_Free)
        {
            painter.drawPixmap(m_enemys[i].m_X, m_enemys[i].m_Y, m_enemys[i].m_enemy1);
        }
    }
    //绘画敌机1
    for (int i = 0; i < ENEMY1_NUM; ++i) {
        if(m_enemys[i].m_Free==false){
            painter.drawPixmap(m_enemys[i].m_X,m_enemys[i].m_Y,m_enemys[i].m_enemy1);
        }
    }
    // 绘画敌机2
    for (int i = 0; i < ENEMY2_NUM; ++i) {
        if (m_enemys2[i].m_Free == false) {
            painter.drawPixmap(m_enemys2[i].m_X, m_enemys2[i].m_Y, m_enemys2[i].m_enemy2);
            // 绘制敌机2的子弹
            for (int j = 0; j < BULLET_ENEMY_NUM; ++j) {
                if (!m_enemys2[i].enemy_bullets[j].m_Free) {
                    painter.drawPixmap(m_enemys2[i].enemy_bullets[j].m_X, m_enemys2[i].enemy_bullets[j].m_Y, m_enemys2[i].enemy_bullets[j].m_bullet2);
                }
            }

        }
    }
    //绘制爆炸1
    for (int i = 0; i <BOMB_ENEMY1_NUM; ++i) {
        if(m_enemy1_bombs[i].m_Free==false){
            painter.drawPixmap(m_enemy1_bombs[i].m_X,m_enemy1_bombs[i].m_Y,m_enemy1_bombs[i].m_pixArr[m_enemy1_bombs[i].m_index]);
        }
    }
    //绘制爆炸2
    for (int i = 0; i <BOMB_ENEMY2_NUM; ++i) {
        if(m_enemy2_bombs[i].m_Free==false){
            painter.drawPixmap(m_enemy2_bombs[i].m_X,m_enemy2_bombs[i].m_Y,m_enemy2_bombs[i].m_pixArr2[m_enemy2_bombs[i].m_index2]);
        }
    }
    //绘画爆炸3
    for (int i = 0; i < BOMB_ME_NUM; ++i) {
        if (!m_meBombs[i].m_Free) {
            painter.drawPixmap(m_meBombs[i].m_X, m_meBombs[i].m_Y,
                               m_meBombs[i].m_pixArr[m_meBombs[i].m_index]);
        }
    }
    //结束画面
    if (m_isPaused) {
        painter.setPen(Qt::white);
        QFont font;
        font.setPointSize(24);
        painter.setFont(font);

        QString text1 = QString("敌机1 击毁数: %1").arg(m_enemy1_destroyedCount);
        QString text2 = QString("敌机2 击毁数: %1").arg(m_enemy2_destroyedCount);

        int x = GAME_WIDTH / 2 - 100;
        int y1 = GAME_HEIGHT / 2 - 50;
        int y2 = y1 + 50;

        painter.drawText(x, y1, 300, 40, Qt::AlignLeft, text1);
        painter.drawText(x, y2, 300, 40, Qt::AlignLeft, text2);
    }
    QFont font;
    font.setPointSize(18);
    font.setBold(true);
    painter.setFont(font);

    // 根据血量设置颜色
    if (m_heroHP >= 3)
        painter.setPen(Qt::green);
    else if (m_heroHP == 2)
        painter.setPen(Qt::yellow);
    else if (m_heroHP == 1)
        painter.setPen(Qt::red);
    else
        painter.setPen(Qt::gray);  // 血量为0或负数时灰色

    QString hpText = QString("我方血量: %1").arg(m_heroHP);
    painter.drawText(10, GAME_HEIGHT - 30, hpText);

}
//鼠标移动飞机
void Widget::mouseMoveEvent(QMouseEvent *event)
{

     if (m_isPaused) return; // 暂停时不响应
     // 只有游戏未暂停时才响应鼠标移动
        int x = event->x() - m_hero.m_Rect.width() * 0.5;
        int y = event->y() - m_hero.m_Rect.height() * 0.5;

        // 边界检测
        if (x <= 0) {
            x = 0;
        }
        if (x > GAME_WIDTH - m_hero.m_Rect.width()) {
            x = GAME_WIDTH - m_hero.m_Rect.width();
        }
        if (y <= 0) {
            y = 0;
        }
        if (y > GAME_HEIGHT - m_hero.m_Rect.height()) {
            y = GAME_HEIGHT - m_hero.m_Rect.height();
        }

        m_hero.setPosition(x, y);

}

void Widget::enemyToscene()
{
    m_recorder++;
    //未出场间隔
    if(m_recorder<ENEMY1_INTERVAL){
        return;
    }
    m_recorder=0;
    for (int i = 0; i < ENEMY1_NUM; ++i) {
        //如果是空闲敌机
        if(m_enemys[i].m_Free){
            m_enemys[i].m_Free=false;
            //坐标+随机数
            m_enemys[i].m_X=rand()%(GAME_WIDTH-m_enemys[i].m_Rect.width());
            m_enemys[i].m_Y=-m_enemys[i].m_Rect.height();
            break;
        }
    }
}
void Widget::enemyToscene2() {
    m_recorder2++;
    // 未出场间隔
    if (m_recorder2 < ENEMY2_INTERVAL) {
        return;
    }
    m_recorder2 = 0;
    for (int i = 0; i < ENEMY2_NUM; ++i) {
        // 如果是空闲敌机
        if (m_enemys2[i].m_Free) {
            m_enemys2[i].m_Free = false;
            // 坐标+随机数
            m_enemys2[i].m_X = rand() % (GAME_WIDTH - m_enemys2[i].m_Rect.width());
            m_enemys2[i].m_Y = -m_enemys2[i].m_Rect.height();
            break;
            Enemyplane2 enemy123;
        }
    }
}
void Widget::collosionDEtection()
{
    //遍历所有出场敌机
    for (int i = 0; i <ENEMY1_NUM; ++i) {
        //如果未出场，下一次循环
        if(m_enemys[i].m_Free){
            continue;
        }
        //遍历所有非空闲子弹、
        for (int j = 0; j < BULLET_MY_NUM; ++j) {
            //空闲子弹，进行下一次循环
            if(m_hero.m_bullets[j].m_Free){
                continue;
            }
            //飞机与子弹相交，发生碰撞
            if(m_enemys[i].m_Rect.intersects(m_hero.m_bullets[j].m_Rect)){
                m_enemys[i].m_Free=true;
                m_hero.m_bullets[j].m_Free=true;
                 m_enemy1_destroyedCount++; // 增加敌机1计数
                //播放爆炸效果
                for (int k = 0; k < BOMB_ENEMY1_NUM; ++k) {
                    if(m_enemy1_bombs[k].m_Free){
                        // m_bombSound->stop();
                        // m_bombSound->play();
                        //空闲的爆炸，播放爆炸
                        m_enemy1_bombs[k].m_Free=false;
                        //更新爆炸坐标
                        m_enemy1_bombs[k].m_X=m_enemys[i].m_X;
                        m_enemy1_bombs[k].m_Y=m_enemys[i].m_Y;
                        break;
                    }
                }
            }
        }

    }
}
void Widget::collosionDEtection2()
{
    //遍历所有出场敌机
    for (int i = 0; i <ENEMY2_NUM; ++i) {
        //如果未出场，下一次循环
        if(m_enemys2[i].m_Free){
            continue;
        }
        //遍历所有非空闲子弹、
        for (int j = 0; j < BULLET_MY_NUM; ++j) {
            //空闲子弹，进行下一次循环
            if(m_hero.m_bullets[j].m_Free){
                continue;
            }
            //飞机与子弹相交，发生碰撞
            if(m_enemys2[i].m_Rect.intersects(m_hero.m_bullets[j].m_Rect)){
                m_enemys2[i].m_Free=true;
                m_hero.m_bullets[j].m_Free=true;
                m_enemy2_destroyedCount++; // 增加敌机2计数
                //播放爆炸2效果
                for (int k = 0; k < BOMB_ENEMY2_NUM; ++k) {
                    if(m_enemy2_bombs[k].m_Free){
                        // m_bombSound->stop();
                        // m_bombSound->play();
                        //空闲的爆炸，播放爆炸
                        m_enemy2_bombs[k].m_Free=false;
                        //更新爆炸坐标
                        m_enemy2_bombs[k].m_X=m_enemys[i].m_X;
                        m_enemy2_bombs[k].m_Y=m_enemys[i].m_Y;
                        break;
                    }
                }
            }
        }

    }
}

void Widget::collosionDEtection3()
{
    for (int i = 0; i < ENEMY2_NUM; ++i) {
        if (!m_enemys2[i].m_Free) {
            for (int j = 0; j < BULLET_ENEMY_NUM; ++j) {
                if (!m_enemys2[i].enemy_bullets[j].m_Free) {
                    if (m_hero.m_Rect.intersects(m_enemys2[i].enemy_bullets[j].m_Rect)) {
                        m_enemys2[i].enemy_bullets[j].m_Free = true;

                        m_heroHP--;

                        if (m_heroHP <= 0) {
                            // 播放爆炸效果
                            for (int k = 0; k < BOMB_ME_NUM; ++k) {
                                if (m_meBombs[k].m_Free) {
                                    m_meBombs[k].m_Free = false;
                                    m_meBombs[k].m_X = m_hero.m_x;
                                    m_meBombs[k].m_Y = m_hero.m_y;

                                    QTimer::singleShot(BOMB_ME_MAX * BOMB_ME_INTERVAL, this, [=]() {
                                        showGameOverScreen();
                                    });
                                    break;
                                }
                            }
                        }
                        return;  // 一次检测只扣一次血
                    }
                }
            }
        }
    }
}
